package health.lm.com.mine.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.rxbus.RxBus;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jakewharton.rxbinding2.view.RxView;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnInputConfirmListener;
import com.vondear.rxtool.RxSPTool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import health.lm.com.component_base.base.event.BusProvider;
import health.lm.com.component_base.base.event.IBus;
import health.lm.com.component_base.base.event.RxBusImpl;
import health.lm.com.component_base.base.mvp.fragment.XFragment;
import health.lm.com.component_base.helper.ImageLoaderHelper;
import health.lm.com.component_base.popup.share.SharePopUtil;
import health.lm.com.component_base.widget.CircleImageView.CircleImageView;
import health.lm.com.data.App;
import health.lm.com.data.AppModel;
import health.lm.com.mine.R;
import health.lm.com.mine.R2;
import health.lm.com.mine.adapter.MineAdapter;
import health.lm.com.mine.entity.MineContentEntity;
import health.lm.com.mine.entity.MineTotalBean;
import health.lm.com.mine.entity.ShareEntity;
import health.lm.com.mine.pop.agreement.AgreeMentPopUtil;
import health.lm.com.mine.present.MinePresent;
import health.lm.com.mine.util.JsonUtil;
import health.lm.com.router.ARouterConstant;

import static android.content.Context.LAYOUT_INFLATER_SERVICE;
import static health.lm.com.mine.entity.MineContentEntity.ABOUTUS;
import static health.lm.com.mine.entity.MineContentEntity.ACTIVATE;
import static health.lm.com.mine.entity.MineContentEntity.CONTACTS;
import static health.lm.com.mine.entity.MineContentEntity.EXPLAIN;
import static health.lm.com.mine.entity.MineContentEntity.SHARE;
import static health.lm.com.mine.entity.MineContentEntity.TEAM;
import static health.lm.com.router.ARouterConstant.FROM_TYPE_INFLUENCE_TEAM;
import static health.lm.com.router.ARouterConstant.FROM_TYPE_PEOPLE_LIST;

/**
 * 我的
 *
 * @author GQI
 */
@Route(path = ARouterConstant.MineFragment)
public class MineFragment extends XFragment<MinePresent> {
    @BindView(R2.id.rlv_mine)
    RecyclerView rlvMine;
    private MineAdapter mineAdapter;
    private MineTotalBean bean;
    private List<MineContentEntity> beanList;
    private CircleImageView iv_user_head;
    private TextView tv_username;
    private TextView tv_user_id;
    private TextView tv_member_num;
    private TextView tv_coin_price;
    private String nickName;
    private boolean notify = false;
    private LinearLayout ll_mine_wallet, ll_mine_card, ll_mine_meet;

    @Override
    public void initData(Bundle savedInstanceState) {
        bean = new MineTotalBean();
        mImmersionBar.statusBarColor(R.color.color_1a1a1a).statusBarDarkFont(false).init();
        //初始化内容adapter
        initContentAdapter();
        getP().getData();
        if (!StringUtils.isEmpty(App.getModel().getNick_name())) {
            nickName = App.getModel().getNick_name();
            tv_username.setText(nickName);
        }
    }


    public String getAvatar() {
        return bean.getInfo().getAvatar();
    }


    /**
     * 初始化内容adapter
     */
    private void initContentAdapter() {
        beanList = new ArrayList<>();
        mineAdapter = new MineAdapter(beanList);
        //添加头部
        mineAdapter.addHeaderView(getHeaderView());
        mineAdapter.openLoadAnimation();
        rlvMine.setLayoutManager(new GridLayoutManager(context, 3));
        rlvMine.setAdapter(mineAdapter);
        mineAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MineContentEntity entity = beanList.get(position);

                if (entity.getType() == ACTIVATE) {
                    AgreeMentPopUtil.getInstance().init(context, rlvMine, "服务协议");
                } else if (entity.getType() == ABOUTUS) {
                    withValueActivity(ARouterConstant.InfoWebviewActivity).withString(ARouterConstant.TOPBAR_TITLE, "关于我们").withInt(ARouterConstant.TYPE, ARouterConstant.ABOUT_US).navigation();
                } else if (entity.getType() == EXPLAIN) {
                    withValueActivity(ARouterConstant.InfoWebviewActivity).withString(ARouterConstant.TOPBAR_TITLE, "使用说明").withInt(ARouterConstant.TYPE, ARouterConstant.INSTRUCTIONS).navigation();
                } else if (entity.getType() == CONTACTS){//我的人脉
                    withValueActivity(ARouterConstant.HLPeopleActivity).withInt(ARouterConstant.FROM_TYPE, FROM_TYPE_PEOPLE_LIST).navigation();
                }else if (entity.getType() == TEAM){//影响力团队
                    withValueActivity(ARouterConstant.HLPeopleActivity).withInt(ARouterConstant.FROM_TYPE, FROM_TYPE_INFLUENCE_TEAM).navigation();
                }else if (entity.getType() == SHARE){//分享
                    getP().getShareData(bean.getInfo().getMobile());
                } else {
                    gotoActivity(entity.getArouter());
                }
            }
        });
    }

    /**
     * 初始化recycleview 头部view
     */
    @SuppressLint("CheckResult")
    private View getHeaderView() {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.item_mine_top, null);
        iv_user_head = view.findViewById(R.id.iv_user_head);
        tv_username = view.findViewById(R.id.tv_username);
        tv_member_num = view.findViewById(R.id.tv_member_num);
        tv_user_id = view.findViewById(R.id.tv_user_id);
        tv_coin_price = view.findViewById(R.id.tv_coin_price);
        ll_mine_card = view.findViewById(R.id.ll_mine_card);
        ll_mine_wallet = view.findViewById(R.id.ll_mine_wallet);
        ll_mine_meet = view.findViewById(R.id.ll_mine_meet);
        //成长积分
        tv_coin_price.setOnClickListener(v -> {
            withValueActivity(ARouterConstant.GrowthIntegralActivity).navigation(context, ARouterConstant.GROWTH_JUMP_SUCCESS);
        });
        //钱包
        RxView.clicks(ll_mine_wallet).throttleFirst(1, TimeUnit.SECONDS).subscribe(v -> {
            new XPopup.Builder(context).asInputConfirm("提示", "请输入二级密码", "请输入密码", new OnInputConfirmListener() {
                @Override
                public void onConfirm(String text) {
                    if (TextUtils.isEmpty(text)) {
                        ToastUtils.showShort("密码不能为空");
                    } else {
                        getP().initWallet(text);
                    }
                }
            }).bindLayout(R.layout.xpopup_center_impl_confirm).show();
        });
        //卡券
        ll_mine_card.setOnClickListener(v -> {
            gotoActivity(ARouterConstant.CardCenterActivity);
        });
        //我的商会
        ll_mine_meet.setOnClickListener(v -> {
            withValueActivity(ARouterConstant.HLMyCompanyActivity).withString("title", "我的商会").navigation();
        });
        view.setLayoutParams(new DrawerLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        return view;
    }

    public void getDataSuccess(MineTotalBean bean) {
        RxSPTool.putString(context, AppModel.my_business_id, bean.getInfo().getBussiness_id());
        this.bean = bean;
        if (!notify) {
            mineAdapter.closeLoadAnimation();
        }
        notifyUserInfo();
        notifyContentAdapter();
    }

    /**
     * 刷新rlv数据
     */
    private void notifyContentAdapter() {
        String json = JsonUtil.getJson(context, "mineclass.json");
        beanList = new Gson().fromJson(json, new TypeToken<ArrayList<MineContentEntity>>() {
        }.getType());
        //判断是否为联盟商 0不是
        if (bean.getInfo().getIs_union() == 0) {
            beanList.remove(8);
        }
        if (bean.getInfo().getIs_send() != 0) {
            beanList.remove(6);
        }
        if (beanList.size() > 0) {
            mineAdapter.setNewData(beanList);
        }
    }

    /**
     * 刷新用户信息
     */
    private void notifyUserInfo() {
        if (!StringUtils.isEmpty(bean.getInfo().getAvatar())) {
            ImageLoaderHelper.getInstance().load(context, bean.getInfo().getAvatar(), iv_user_head);
        }
        nickName = bean.getInfo().getReal_name();
        App.getModel().setNick_name(nickName);
        //用户名
        tv_username.setText(bean.getInfo().getReal_name());
        //所属商会名称
        tv_user_id.setText(bean.getInfo().getBussiness_title());
        /*会员职位*/
        tv_member_num.setText(bean.getInfo().getDuties_title());
        String price = "<font color=#ffffff>成长积分:</font><font color=#e1b65c> " + bean.getInfo().getCredit() + "</font>";
//        //兑换规则备注
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            tv_coin_price.setText(Html.fromHtml(price, Html.FROM_HTML_MODE_COMPACT));
        } else {
            tv_coin_price.setText(Html.fromHtml(price));
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getP().getData();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    public MinePresent newP() {
        return new MinePresent();
    }

    public void jumpWallet(String url) {
        withValueActivity(ARouterConstant.JSWalletWebActivity).withString("url", url).navigation();
    }

    public void share(ShareEntity pEntity) {
        SharePopUtil.getInstance().showContent(context,rlvMine
                ,pEntity.getTitle()
                ,pEntity.getContent()
                ,pEntity.getAvatar()
                ,pEntity.getUrl());
    }

}
